package com.yi.wood.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * @author MoYi
 * Created time 2019/5/29 17:08
 * 图片与BASE64互转
 */
public class ImageUtil {

    private static final int DEFAULT_WIDTH = 300;
    private static final int DEFAULT_HEIGHT = 100;

    public static String imageToBase64(BufferedImage image) throws Exception {
        ByteArrayOutputStream bao = new ByteArrayOutputStream();
        ImageIO.write(image, "png", bao);
        BASE64Encoder encoder = new BASE64Encoder();
        String base64Image = encoder.encodeBuffer(bao.toByteArray()).trim();
        //删除 \r\n
        return base64Image.replaceAll("\n", "").replaceAll("\r", "");
    }

    public static BufferedImage base64StringToImage(String base64String) {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] bytes = decoder.decodeBuffer(base64String);
            ByteArrayInputStream stream = new ByteArrayInputStream(bytes);
            return ImageIO.read(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static BufferedImage createVerCodeImage(String chars) {
        int padding = 0;
        BufferedImage image = new BufferedImage(DEFAULT_WIDTH, DEFAULT_HEIGHT, BufferedImage.TYPE_INT_BGR);
        Graphics2D graphics2D = image.createGraphics();
        graphics2D.setColor(Color.WHITE);
        graphics2D.fillRect(padding, padding, DEFAULT_WIDTH, DEFAULT_HEIGHT);

        graphics2D.setColor(Color.black);
        graphics2D.setFont(new Font("Fixedays", Font.PLAIN, DEFAULT_HEIGHT - padding));
        graphics2D.drawString(chars, padding, DEFAULT_HEIGHT - padding);
        return image;
    }

    /**
     * 读取图片，切图后滑动切块验证
     *
     * @param file   图片文件位置
     * @param left   切图左偏移量
     * @param top    切图上偏移量
     * @param width  切图长度
     * @param height 切图高度
     * @return 图片对象
     */
    public static BufferedImage[] createVerCodeByFileImage(File file, int left, int top, int width, int height) throws IOException {
        BufferedImage[] images = new BufferedImage[2];
        BufferedImage bufferedImage = ImageIO.read(file);

        BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_4BYTE_ABGR);
        int targetX = 0;
        int targetY = 0;
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                targetX = left + i;
                targetY = top + j;
                int oriRgb = bufferedImage.getRGB(targetX, targetY);

                // 复制抠图的颜色
                target.setRGB(i, j,  oriRgb);
                // 将抠图位置颜色变淡
                bufferedImage.setRGB(targetX,targetY, oriRgb & 0x00ffffff);
            }
        }
        // 小图
        images[0] = target;
        // 大图
        images[1] = bufferedImage;

        return images;
    }
}
